package org.example.demo01;

import org.example.demo01.service.DispatchService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;
import org.springframework.beans.factory.annotation.Autowired;
import javax.sql.DataSource;
import java.sql.*;

@SpringBootApplication
public class Demo01Application implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private DispatchService dispatchService;

    public static void main(String[] args) {
        SpringApplication.run(Demo01Application.class, args);
    }

    @Override
    public void run(String... args) {
        generatePieceRecords();
        dispatchService.schedulePieces();
    }

    private void generatePieceRecords() {
        // 1. 设置固定年月为202505（不使用当前时间）
        final String FIXED_YEAR_MONTH = "202505";

        // 2. 清空原有数据
        try (Connection conn = dataSource.getConnection();
             Statement stmt = conn.createStatement()) {
            stmt.execute("TRUNCATE TABLE piece");
        } catch (SQLException e) {
            System.err.println("清空表失败:");
            e.printStackTrace();
            return;
        }

        // 3. 生成新数据
        String selectSql = "SELECT pid, amount FROM pplanitem ORDER BY id";
        String insertSql = "INSERT INTO piece (id, pid) VALUES (?, ?)";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement selectStmt = conn.prepareStatement(selectSql);
             PreparedStatement insertStmt = conn.prepareStatement(insertSql);
             ResultSet rs = selectStmt.executeQuery()) {

            int globalSequence = 1; // 序号从1开始

            while (rs.next()) {
                String pid = rs.getString("pid");
                int amount = rs.getInt("amount");

                for (int i = 1; i <= amount; i++) {
                    // 生成固定年月的件号：ps202505001
                    String pieceId = String.format("ps%s%03d", FIXED_YEAR_MONTH, globalSequence++);

                    insertStmt.setString(1, pieceId);
                    insertStmt.setString(2, pid);
                    insertStmt.addBatch();

                    // 每100条提交一次
                    if (globalSequence % 100 == 0) {
                        insertStmt.executeBatch();
                    }
                }
            }

            // 提交剩余记录
            insertStmt.executeBatch();
            System.out.println("成功生成 " + (globalSequence-1) + " 条记录，件号示例: ps" + FIXED_YEAR_MONTH + "001");

        } catch (SQLException e) {
            System.err.println("生成记录失败:");
            e.printStackTrace();
        }
    }
}